#include "ui.h"

#include <time.h>
#include "oled_12832.h"
#include "gnss.h"

#define REFRESH_INTERVAL 1000 //10s

static GnssNmea_t* gnssInfo = 0;

static void uiStartTimerRefresh(uint32_t interval);

static void OnTimerRefresh(void* param)
{
    TIME_System_t calendar;
    static uint8_t count = 0;
    static uint8_t buff[10] = {0}; // 经常允许，就不要一直分配释放了

    // 刷新图标
    Oled_ShowIcon16X16(0, 0, &kIconGPRS[0][0]);
    Oled_ShowIcon16X16(0, 16, &kIconConnect[0][0]);

    if (gnssInfo->IsVaild)
    {
        if (gnssInfo->Speed > 10)
            Oled_ShowIcon16X16(0, 32, &kIconGPS[kIconLocatedMove][0]);
        else
            Oled_ShowIcon16X16(0, 32, &kIconGPS[kIconLocatedStatic][0]);
    }
    else
        Oled_ShowIcon16X16(0, 32, &kIconGPS[kIconUnlocated][0]);

    // 刷新时间 2s显示 年月日 3秒显示时分秒 如此循环
    TIME_GetLocalTime(&calendar);
    switch (count) {
        default:
            count = 0; // 故意地没有break
        case 1:
        case 0:
            snprintf(buff, 10, "%2d-%02d-%02d", 
                calendar.year % 100, calendar.month,  calendar.day);
            break;
        case 2:
        case 3:
        case 4:
            snprintf(buff, 10, "%02d:%02d:%02d",
                calendar.hour, calendar.minute, calendar.second);
            break;
    }

    buff[9] = 0;

    count = (++count) % 5;

    Oled_ShowString8X16(2, 0, buff);

    // 刷新速度
    snprintf(buff, 10, "%2dkm/h", gnssInfo->Speed / 10);
    buff[9] = 0;
    Oled_ShowString8X16(2, 80, buff);

    uiStartTimerRefresh(REFRESH_INTERVAL);
}

static void uiStartTimerRefresh(uint32_t interval)
{
    OS_StartCallbackTimer(MainTaskHandle, interval, OnTimerRefresh, NULL);
}

static void uiEventPopWindows(UiEvent_t* pEvent)
{
      
}

// 事件处理
static void uiEventDispatch(UiEvent_t* pEvent)
{
    switch(pEvent->EventId)
    {
        case kUiEventPopWindows:
            uiEventPopWindows(pEvent);
            break;
        default:
            break;
    }
}

void Ui_TaskEntry(void *pData)
{
    UiEvent_t* event = NULL;
    
    gnssInfo = gnss_GetInfo();

    uiStartTimerRefresh(REFRESH_INTERVAL);
    
    while (1) {
        if (OS_WaitEvent(UiTaskHandle, (void**)&event, OS_TIME_OUT_WAIT_FOREVER)) {
            uiEventDispatch(event);
            OS_Free(event->EventData);
            OS_Free(event);
        }
        OS_Sleep(200);
    }
}
